package com.hidquat;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbConstants;
import android.os.Handler;
import android.os.Message;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;

import android.content.Context;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.hardware.usb.UsbRequest;
import android.hardware.usb.UsbManager;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

/**
 * Created by hesong on 2017/4/15.
 */

public class UsbThread extends Thread {

    private Handler mHandle;
    private int progress;
    private UsbManager mManager;
    private UsbDevice mUsbDevice = null;
    private UsbInterface mInterface;
    private UsbDeviceConnection mDeviceConnection;
    private UsbEndpoint mEndpointIn;
    private UsbEndpoint mEndpointOut;
    private static final int deviceVID = 0x0483;
    private static final int devicePID = 0x5750;
    private boolean alive;

    UsbThread( UsbManager manager, UsbDevice usbDevice, Handler handler){
        mManager = manager;
        mUsbDevice = usbDevice;
        mHandle = handler;
        if (mUsbDevice == null) {
            return;
        }

        alive = true;
        findIntfAndEpt();
    }

    public void resum()
    {
        alive = false;
    }

    private byte[] Receiveytes;
    @Override
    public void run() {
        int ret = -100;
        progress = 0;
        while (alive && progress <= 100) {
            try {
                sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Receiveytes = new byte[32];
            if(epIn != null){
                ret = mDeviceConnection.bulkTransfer(epIn, Receiveytes,
                        Receiveytes.length, 10000);
                progress = ret;
            }

            Message message = Message.obtain();
            message.obj = progress;
            message.what = 2;
            mHandle.sendMessage(message);
            //progress++;
        }
    }

    // 寻找接口和分配结点
    private void findIntfAndEpt() {
        if (mUsbDevice == null) {
            DisplayToast("没有找到设备");
            return;
        }
        for (int i = 0; i < mUsbDevice.getInterfaceCount();) {
            // 获取设备接口，一般都是一个接口，你可以打印getInterfaceCount()方法查看接
            // 口的个数，在这个接口上有两个端点，OUT 和 IN
            UsbInterface intf = mUsbDevice.getInterface(i);
            DisplayToast(i + " " + intf);
            mInterface = intf;
            break;
        }

        if (mInterface != null) {
            UsbDeviceConnection connection = null;
            // 判断是否有权限
            if (mManager.hasPermission(mUsbDevice)) {
                // 打开设备，获取 UsbDeviceConnection 对象，连接设备，用于后面的通讯
               connection = mManager.openDevice(mUsbDevice);
                if (connection == null) {
                    return;
                }
                if (connection.claimInterface(mInterface, true)) {
                    DisplayToast("找到接口");
                    mDeviceConnection = connection;
                    // 用UsbDeviceConnection 与 UsbInterface 进行端点设置和通讯
                    getEndpoint(mInterface);
                } else {
                    connection.close();
                    DisplayToast("没找到接口");
                }
           } else {
                DisplayToast("没有权限");
            }
        } else {
            DisplayToast("没有找到接口");
        }
    }

    private UsbEndpoint epOut;
    private UsbEndpoint epIn;
    private void getEndpoint( UsbInterface intf) {
        for ( int i=1; i<intf.getEndpointCount(); i++ ) {
            if (intf.getEndpoint(i).getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
                if (intf.getEndpoint(i).getDirection() == UsbConstants.USB_DIR_IN) {
                    epIn = intf.getEndpoint(i);
                }else if(intf.getEndpoint(i).getDirection() == UsbConstants.USB_DIR_OUT){
                    epOut = intf.getEndpoint(i);
                }
            }
        }
    }

    public void DisplayToast(CharSequence str) {
        Message message = Message.obtain();
        message.obj = str;
        message.what = 1;
        mHandle.sendMessage(message);
    }
}
